//


import UIKit

import SVProgressHUD
import AFNetworking

let switfRootViewController = "switfRootViewController"

//  微博appKey
let WeiboAppKey = "1182785320"
//  微博appsecret
let WeiboAppSecret = "1606843f6c67acf9cd0771db17fc1ac2"
//  微博授权回调页
let WeiboRedirect_Uri = "http://www.itcast.cn"


class CZOAuthViewController: UIViewController {
    
    // MARK:    --懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        //  自定义视图
        webView.delegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupNavUI()
        requestOAuthLogin()
    }
    
    private func requestOAuthLogin() {
        //  请求地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        print(url)
        //  准备请求对象
        let request = NSURLRequest(URL: NSURL(string: url)!)
        //  加载请求
        webView.loadRequest(request)
    
    }
    
    
    private func setupNavUI() {
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
    
    }
    
    // MARK: -- 点击事件
    @objc private func cancelAction() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillAction() {
        print("自动填充")
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'hao123guohaibin@163.com'; document.getElementById('passwd').value = 'guohaibin012'")
    }
}


extension CZOAuthViewController: UIWebViewDelegate {
    
    //  将要加载请求  http://www.itcast.cn/?code=f6cea50fbbf21cc1c7ce4a3030966afe
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL else {
            return false
        }
        
        //  代码执行到此,我们的url一定有值
      
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            return true
        }
        
        print(url.absoluteString)
        //
        
        if let query = url.query where query.hasPrefix("code=") {
            //  截取code
            let code = query.substringFromIndex("code=".endIndex)
            
            print("我想要的code: " + code)
            
            //            requestAccesstoken(code)
            
            CZUserAccountViewModel.shareUserAccount.requestAccesstoken(code, callBack: { (isSuccess) -> () in
                if isSuccess {
                    print("登录成功")
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //  发送通知
                        NSNotificationCenter.defaultCenter().postNotificationName(switfRootViewController, object: self)
                    })
                    
                    
                } else {
                    print("登录失败")
                }
            })
            
            
        } else {
            //  进入取消回调页
            dismissViewControllerAnimated(true, completion: nil)
        }
        
        
        return false
        
    }
    //  开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //  加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //  加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}























